package com.movies.service.controller.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import com.movies.service.entity.Save;
import com.movies.service.entity.User;
import com.movies.service.mapper.SaveMapper;
import com.movies.service.service.SaveService;
import com.movies.service.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/admin/save")
@SaCheckLogin
@SaCheckRole("ADMIN")
public class AdminSaveController {

    @Autowired
    private SaveService saveService; // 仅分页
    @Autowired
    private SaveMapper saveMapper;   // 原生 SQL CRUD
    @Autowired
    private UserService userService; // 用于按用户名模糊过滤

//    收藏分页查询 按用户ID/电影ID精确筛选，按用户名/电影名模糊筛选
    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1") Integer pageNo,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) Long uid,
                       @RequestParam(required = false) Long mid,
                       @RequestParam(required = false) String uname,
                       @RequestParam(required = false) String mname) {
        LambdaQueryWrapper<Save> wrapper = new LambdaQueryWrapper<>();
        // 精确筛选
        wrapper.eq(uid != null, Save::getUid, uid)
                .eq(mid != null, Save::getMid, mid)
                // 电影名模糊
                .like(mname != null && mname.trim().length() > 0, Save::getMname, mname);
        // 用户名模糊：先查出匹配的用户ID，再 in 过滤
        if (uname != null && uname.trim().length() > 0) {
            List<User> users = userService.list(new LambdaQueryWrapper<User>()
                    .like(User::getUname, uname)
                    .select(User::getId));
            List<Long> uidList = users.stream().map(User::getId).collect(Collectors.toList());
            if (uidList.isEmpty()) {
                // 无匹配用户名则直接返回空分页
                Page<Save> empty = new Page<>(pageNo, pageSize);
                empty.setRecords(Collections.emptyList());
                empty.setTotal(0);
                return Result.success("查询成功", empty);
            }
            wrapper.in(Save::getUid, uidList);
        }
        Page<Save> page = saveService.page(new Page<>(pageNo, pageSize), wrapper);
        return Result.success("查询成功", page);
    }

//    根据ID获取收藏详情
    @GetMapping("/{id}")
    public Result get(@PathVariable Long id) {
        return Result.success(saveMapper.selectSaveById(id));
    }

//    新增收藏记录
    @PostMapping("/create")
    public Result create(@RequestBody Save save) {
        int rows = saveMapper.insertSave(save);
        return rows > 0 ? Result.success("新增成功") : Result.error(Constants.CODE_600, "新增失败");
    }

//    更新收藏记录
    @PutMapping("/update")
    public Result update(@RequestBody Save save) {
        int rows = saveMapper.updateSaveById(save);
        return rows > 0 ? Result.success("更新成功") : Result.error(Constants.CODE_600, "更新失败");
    }

//    删除收藏记录
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        int rows = saveMapper.deleteSaveById(id);
        return rows > 0 ? Result.success("删除成功") : Result.error(Constants.CODE_600, "删除失败");
    }

//    批量删除收藏记录
    @DeleteMapping("/batch")
    public Result deleteBatch(@RequestBody java.util.List<Long> ids) {
        int rows = saveMapper.deleteSavesByIds(ids);
        return rows > 0 ? Result.success("批量删除成功") : Result.error(Constants.CODE_600, "批量删除失败");
    }
}